import { createHash, randomBytes } from 'crypto'

export interface IPayLoad {
  id: number
  fp: string
  salt: string
  secret: string
}

export function encodePassword(fromPassword: string) {
  const md5 = createHash('md5')
  const salt = randomBytes(64).toString('base64')
  const saltPassword = fromPassword + salt
  const secret = md5.update(saltPassword).digest('hex')
  return [salt, secret]
}

export function validatePassword(
  fromPassword: string,
  salt: string,
  secret: string,
) {
  const md5 = createHash('md5')
  const saltPassword = fromPassword + salt
  const _secret = md5.update(saltPassword).digest('hex')
  return _secret === secret
}
